package eclipse.server;
import eclipse.lib.scripting.*;
import eclipse.*;
/**
 * Encodes and decodes all messages sent to the Server.
 */
public class ByteEncoder 
{
	public static byte[] print(String sOutput)
	{
		byte[] comCode = new byte[3 + sOutput.length()];
		byte[] bString = ByteInterpreter.stringToByteArray(sOutput);
		comCode[0] 				= Constants.com_START;
		comCode[1]				= Constants.com_PRINT;
		comCode = ByteInterpreter.appendToByteArray(comCode, bString, 2);
		comCode[comCode.length - 1] = Constants.com_END;
		return comCode;
	}
	
	public static void decode(int index, byte[] comCode)
	{
		int offset_END;
		int offset_START;
		byte[] command, msg;
		for(int s = 0; s < comCode.length; s++)
			System.out.print(comCode[s] + " ");
		
		for(int a = 0; a < comCode.length; a++)
		{
			if(comCode[a] == Constants.com_START)
			{					
				offset_START = a + 1;
				for(int b = offset_START; b < comCode.length; b++)				
				{
					if(comCode[b] == Constants.com_END)					
					{
						offset_END = b;
						command = ByteInterpreter.getSubByteArray(comCode, offset_START, offset_END);
						if(command[0] == Constants.com_MAXDATA)
						{
							msg = sendMax();
							Database.client[index].sendMsg(ByteInterpreter.byteArrayToString(msg));
						}
						break;
					}
				}
			}
		}
	}
	public static byte[] sendMax()
	{
		System.out.println("request max");
		byte[] comCode = new byte[7];
		byte[] MaxPlayers = ByteInterpreter.intToByteArray(Database.MAXPLAYERS);
		comCode[0] = Constants.com_START;
		comCode[1] = Constants.com_MAXDATA;
		comCode = ByteInterpreter.appendToByteArray(comCode, MaxPlayers, 2);
		comCode[6] = Constants.com_END;
		return comCode;
	}
}
